package XMLTest;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

//public class test2 {
//    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
//        DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
//        DocumentBuilder builder=factory.newDocumentBuilder();
//        Document doc=builder.parse("src/XMLTest/my.xml");
//        NodeList peoples= doc.getElementsByTagName("people");
//for (int i=0;i< peoples.getLength();i++){
//    Node node= peoples.item(i);
//    NamedNodeMap attributes = node.getAttributes();
//    for (int j = 0; j < attributes.getLength() ; j++) {
//        System.out.println(attributes.item(j).getNodeName() + "=" + attributes.item(j).getNodeValue());
//    }
//    NodeList childs=doc.getChildNodes();
//    for (int j = 0; j < childs.getLength() ; j++) {
//        System.out.println(childs.item(j).getNodeName() + "=" + childs.item(j).getNodeValue());
//    }
//}
//    }
//}
public class test2 {
    public static void main(String[] args) throws ParserConfigurationException, IOException, org.xml.sax.SAXException {
        // 创建 DocumentBuilderFactory 实例
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // 创建 DocumentBuilder 实例
        DocumentBuilder builder = factory.newDocumentBuilder();
        // 解析指定的 XML 文件
        Document doc = builder.parse("src/XMLTest/my.xml");

        // 获取所有名为 "people" 的元素
        NodeList peoples = doc.getElementsByTagName("people");

        // 遍历所有 "people" 元素
        for (int i = 0; i < peoples.getLength(); i++) {
            Node node = peoples.item(i);

            // 处理元素的属性
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                NamedNodeMap attributes = node.getAttributes();
                for (int j = 0; j < attributes.getLength(); j++) {
                    Node attribute = attributes.item(j);
                    System.out.println(attribute.getNodeName() + "=" + attribute.getNodeValue());
                }

                // 处理元素的子节点
                NodeList childs = node.getChildNodes();
                for (int k = 0; k < childs.getLength(); k++) {
                    Node child = childs.item(k);
                    if (child.getNodeType() == Node.ELEMENT_NODE) {
                        System.out.println(child.getNodeName() + "=" + child.getTextContent());
                    }
                }
            }
        }
    }
}